<template>
	<view>
		<view class="page" :style="{height: screenHeight + 'px'}">
			<!-- 主体部分 -->
			<view class="main">
				<!-- 选择品类 -->
				<view class="main_left">
					<view class="main_left_head u-border-bottom u-border-right">
						<u-icon size="30rpx" name="grid-fill"></u-icon>
						<text class="u-font-xl u-m-l-10">选择回收物</text>
					</view>
					<view class="main_left_content">
						<goods-vertical-box ref="goodsVerticalBox" :defaultChoose="defaultChoose" :orderId="id" @confirm="confirmChoose" style="display: flex;"></goods-vertical-box>
					</view>
				</view>
				<!-- 右边信息展示 -->
				<view class="main_right">
					<!-- 显示重量 -->
					<view class="main_right_weight">
						<view class="main_right_weight_header u-border-bottom u-flex">
							<u-icon size="30rpx" name="file-text-fill"></u-icon>
							<text class="u-font-xl u-m-l-10">当前磅秤重量</text>
						</view>
						<!-- #ifdef APP -->
						<view class="main_right_weight_number">
							<text class="num" :class="isSteady?'yes':'no'">{{weight}}</text>
							<text class="unit">KG</text>
						</view>
						<!-- #endif -->
						<!-- 环形称重计 -->
						<!-- <div class="circle-progress-box">
							<div class="circle-bg"></div>
							<div class="circle-progress">
								<div class="progress-bar" :style="{'--progress':percent}"></div>
							</div>
							<div class="scale"></div>
							<view class="weight">
								<view>
									<text class="num" :class="isSteady?'yes':'no'">{{weight}}</text>
									<text class="unit">KG</text>
								</view>
								<view class="u-p-b-36">
									<text class="u-tips-color u-font-16">磅秤重量</text>
								</view>
							</view>
							<view class="pointer" :style="{'transform': 'rotate('+angle+')'}"></view>
						</div> -->
					</view>
					<!-- 收货单信息 -->
					<view class="main_right_userInfo">
						<view class="main_right_userInfo_header u-border-bottom">
							<!-- <text class="iconfont icon-dingdanguanli u-font-30"></text> -->

							<view class="u-flex">
								<view class="u-flex u-flex-1">
									<u-icon size="30rpx" name="file-text-fill"></u-icon>
									<text class="u-font-xl u-m-l-10">当前收货单</text>
								</view>
								<view class="u-flex" @click="telSearch.show = true">
									<u-input style="width: 35%;width: 200rpx;height: 40rpx;" prefixIcon="search" prefixIconStyle="font-size: 22px;color: #909399" placeholder="手机号搜索用户" size="mini" :disabled="true"/>
								</view>
							</view>
						</view>
						<view class="u-flex">
							<view class="u-flex-1">
								<view class="user-msg u-flex u-border-bottom">
									<u-avatar :src="''" :size="30"></u-avatar>
									<view class="list u-flex-1 u-p-l-15">
										<view class="u-font-sm u-tips-color">收货客户</view>
										<view class="u-font-sm">
											<text v-if="userInfo.id > 0">{{userInfo.name}}
												<text v-if="userInfo.code">(卡号：{{userInfo.code}})</text>
												<text v-if="userInfo.mobile">(电话号码：{{userInfo.mobile}})</text>
											</text>
											<text v-else>请刷卡或刷客户二维码</text>
										</view>
									</view>
								</view>
							</view>
						</view>
					</view>
					<!-- 回收品类列表 -->
					<view class="main_right_table">
						<view class="u-p-10" v-if="hasRecore">
							<u-tag text="已恢复上次未完成的数据" type="warning" icon="error-circle-fill"></u-tag>
						</view>
						<goods-table-list ref="goodsTableList" :uploadPic="false" @update="getTotal" @pic="getPic"></goods-table-list>
						<view class="u-p-t-60" v-if="goodsList.length == 0">
							<u-empty icon-size="80" text="请选择回收物,小程序用户请扫码" mode="list"></u-empty>
						</view>
					</view>
					<!-- 底部按钮 -->
					<view class="bottom-box">
						<view class="fixed-container">
							<view class="total u-m-b-30">
								<text class="total-price">
									<text class="unit">￥</text>
									<text class="num">{{total}}</text>
								</text>
								<view class="btn u-tips-color" style="background: transparent;color: #909399;" @click="cancelOrder">取消</view>
								<view class="btn" @click="confirmOrderShow">提交结账</view>
							</view>
						</view>
						<view class="fixed-placeholder"></view>
					</view>
				</view>
			</view>
		</view>
		<!-- 操作提示 -->
		<alert-modal ref="alert" @close="closeModal" @confirm="confirmModal"></alert-modal>
		<!-- 读取读卡器扫码器的值 -->
		<keydownReceive v-if="devices.setting.scanCodeAndICisNative" @getCode="getCode"></keydownReceive>
		<!-- 确认订单信息 -->
		<u-popup :show="confirmOrder" mode="bottom" round="14" :closeable="true" @close="confirmOrder = false" :zIndex="10075">
			<view class="confirm-order u-p-t-40">
				<view class="u-text-center u-p-t-30">
					<view class="u-m-r-10 u-m-b-10">
						<u-icon name="question-circle-fill" size="80" color="#f0ad4e" style="margin: 0 auto;display: inline-block;"></u-icon>
					</view>
					<view class="u-font-36">确认回收</view>
				</view>
				<view class="u-p-b-60 u-text-center u-font-28 u-tips-color"><text>请确认以下订单信息</text></view>
				<view class="divider"></view>
				<view class="settlement-List">
					<scroll-view :scroll-y="true" style="max-height: 500px;">
						<view class="u-flex item" v-for="(item,index) in goodsList" :key="index">
							<view class="u-flex-1 u-text-left">
								<view class="u-font-28 u-main-color u-m-b-10">
									<text class="goods-name">{{item.name}}</text>
								</view>
								<view class="u-font-24 u-tips-color">
									<text>单价：￥{{item.price}}元/kg</text>
									<text class="u-m-l-30">重量：{{item.weight}}KG</text>
								</view>
								<view v-if="item.typeRemarks" class="u-p-t-10">
									<u-tag :text="`备注：${item.typeRemarks}`" mode="light" type="info"/>
								</view>
							</view>

							<view class="u-p-t-10">
								<text class="u-font-28">
									<text class="goods-price">￥{{(item.price*item.weight).toFixed(2)}}</text>
								</text>
							</view>
						</view>
					</scroll-view>
					<view class="u-flex item" v-if="pic.length > 0">
						<view class="u-flex-1 u-text-left">
							<view class="u-font-28 u-main-color u-m-b-10 u-flex-1">
								<text class="goods-name">现场拍照</text>
							</view>
							<view class="u-font-24 u-tips-color">
								<text>共{{pic.length}}张</text>
							</view>
						</view>
						<u-image :src="imgURL(pic[0])" width="200" height="100" @click="seePhoto(0)">
							<!-- <u-loading slot="loading"></u-loading> -->
						</u-image>
					</view>
				</view>

				<!-- <view class="divider"></view> -->
				<view class="navigation-sticky-box">
					<view class="navigation u-p-b-0 u-m-b-0">
						<view class="left">
							<view class="u-text-left u-flex-1 u-p-l-40">
								<view><text class="u-font-24 u-tips-color">合计：</text></view>
								<text class="text-orange goods-price">￥</text>
								<text class="u-font-36 goods-price">{{total==0?'--':total}}</text>
							</view>
						</view>
						<view class="right" @click="startConfimCreate">
							<view class="buy btn u-line-1 bg-gradual-blue">确认提交</view>
						</view>
					</view>
				</view>
			</view>
		</u-popup>
		<!-- 提示信息 -->
		<u-popup :show="msgShow" mode="center" round="14" :closeable="true" @close="msgShow = false">
			<view class="u-p-60">
				<view class="u-w-100" style="margin: 0 auto">
					<u-icon name="scan" size="100" color="#909399" style="display: inline-block;"></u-icon>
				</view>
				<view class="u-p-t-20 u-p-r-60 u-p-l-60">
					<text class="u-font-32">{{msg}}</text>
				</view>
			</view>
		</u-popup>
		<!-- 手机号搜索 -->
		<u-popup :show="telSearch.show" mode="bottom" round="14" :closeable="true" @close="telSearch.show = false" :zIndex="10075">
			<view class="u-p-t-30 u-p-b-30 u-text-center"><text class="u-font-32">手机号搜索用户</text></view>
			<view class="search-list">
				<view class="u-flex u-m-t-2 u-p-l-30 u-p-r-30">
					<view class="u-flex-1 u-m-r-30">
						<u-input v-model="telSearch.key" type="number" :focus="telSearch.focus" :autoBlur="true"
							:adjustPosition="false" placeholder="请输入用户手机号检测" size="mini" clearable
							@change="(value)=>{searchKey(value)}" />
					</view>
					<u-button type="primary" @click="searchKey(telSearch.key)" class="u-w-100"><u-icon size="28" color="#fff" name="search" class="u-tips-color"></u-icon></u-button>
				</view>
				<view class="u-flex u-justify-content u-p-20" v-if="loading">
					<u-loading-icon text="加载中"></u-loading-icon>
				</view>
				<view v-if="telSearch.searchList.length > 0">
					<view class="u-m-l-30 u-m-t-10 u-m-b-10"><text class="u-tips-color u-font-24">共{{telSearch.searchList.length}}条搜索结果</text></view>
					<u-cell-group>
						<u-cell 
							v-for="(item,index) in telSearch.searchList"
							:key="item.qrcode"
							:title="item.name" 
							:value="item.mobile"
							@click="chooseUser(item)"
							:isLink="true">
						</u-cell>
					</u-cell-group>
				</view>
				<view v-if="telSearch.bindenterprises.length > 0">
					<view class="u-m-l-30 u-m-t-10 u-m-b-10"><text class="u-tips-color u-font-24">共{{telSearch.bindenterprises.length}}条与之相关的企业</text></view>
					<u-cell-group>
						<u-cell 
							v-for="(item,index) in telSearch.bindenterprises"
							:key="item.qrcode"
							:title="item.name" 
							:label="item.department?'所属部门：'+item.department:'管理员'"
							:value="item.type"
							@click="chooseUser(item)"
							:isLink="true">
						</u-cell>
					</u-cell-group>
				</view>
								
				<view class="u-p-60" v-if="!loading && telSearch.searchList.length == 0">
					<u-empty :text="tips" mode="search"></u-empty>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import {
		commonStore
	} from "@/store/common.js"
	// #ifdef APP-PLUS
	import {
		devicesStore
	} from "@/store/devices.js"
	// #endif
	// 引入配置
	import config from '@/util/config.js'
	import tool from "@/util/tool.js"
	
	// 弹窗提示消息
	import alertModal from "@/components/alert-modal/alert-modal.nvue"

	export default {
		components:{
			alertModal
		},
		setup() {
			const common = commonStore()
			// #ifdef APP-PLUS
			const devices = devicesStore()
			// #endif
		
			return {
				common,
				// #ifdef APP-PLUS
				devices
				// #endif
			}
		},
		data() {
			return {
				isDev: false,
				hasRecore: false,
				id: 0,
				loading: false,
				details: [],
				screenHeight: 0,
				statusBarHeight: 0,
				total: 0,
				// 头部时间
				pic: [], //照片数组
				tempPic: [],
				payTypeShow: false,
				payType: 2, //1:微信小程序,2:线下支付
				msgShow: false,
				msg: '请店员登录',
				userInfo:{
					id: 0,
					code: '',
					details:{}
				},
				orderForm: {},
				confirmOrder:false,
				// 手机号搜索用户
				telSearch:{
					show: false,
					isNotReg: false,
					focus: false,
					key: '',
					searchList: [],
					bindenterprises: []
				},
				tips: "没有搜索结果",
				defaultChoose: [],
				printForm:{}
			}
		},
		computed: {
			header() {
				return this.common.Authorization
			},
			userdetail() {
				return this.common.userdetail
			},
			info(){
				return this.common.info
			},
			goodsList(){
				return this.common.goodsList
			},
			percent(value){
				return parseFloat(this.weight) / 100 * 100 / 2 + '%'
			},
			angle(){
				return parseFloat(this.weight) / 100 * 180 + 'deg'
			},
			// #ifdef APP-PLUS
			weight() {
				return this.devices.devices.Weigh.value
			},
			isSteady(){
				//磅秤稳定状态
				return this.devices.devices.Weigh.isStable
			},
			icCode(){
				return this.devices.devices.IC.value
			},
			scanCode(){
				return this.devices.devices.ScanCode.value
			}
			// #endif
		},
		watch: {
			orderForm:{
				handler(newVal, oldVal) {
					this.saveTempData()
				},
				deep: true
			},
			goodsList:{
				handler(newVal, oldVal) {
					this.getTotal(newVal)
					this.saveTempData()
				},
				deep: true
			},
			icCode(code) {
				// 监听读卡器数据
				let route = getCurrentPages()[getCurrentPages().length - 1].route
				if (code != '' && route == 'pages/batch/batch') {
					console.log(`icCodeGetFor-${route}`, code)
					this.IC(code);
					// 延迟用于watch间隔读取
					const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
					delay(1000).then(() => {
						console.log('延时1000ms执行')
					    this.devices.devices.IC.value = ''
					});
				}
			},
			scanCode(code) {
				// 监听扫码器数据
				let route = getCurrentPages()[getCurrentPages().length - 1].route
				if (code != '' && route == 'pages/batch/batch') {
					console.log(`scanCodeGetFor-${route}`, code)
					this.scan(code);
					// 延迟用于watch间隔读取
					const delay = (ms) => new Promise(resolve => setTimeout(resolve, ms));
					delay(1000).then(() => {
						console.log('延时1000ms执行')
					    this.devices.devices.ScanCode.value = ''
					});
				}
			},
			"telSearch.show"(value){
				this.telSearch.key = ''
				this.telSearch.focus = value
			}
		},
		onReady() {
			if (process.env.NODE_ENV === 'development') {
				console.log('当前运行在开发环境');
				uni.showToast({
					title: '当前运行在开发环境',
					icon: 'none',
					duration: 5000
				})
				this.isDev = true
			} else if (process.env.NODE_ENV === 'production') {
				console.log('当前运行在生产环境');
				this.isDev = false
			}
			
			this.statusBarHeight = uni.getSystemInfoSync().statusBarHeight
			this.screenHeight = uni.getSystemInfoSync().safeArea.height - this.statusBarHeight * 2
		},
		onShow() {
			// #ifdef H5
			// this.IC('2555860788')
			// #endif
		},
		onLoad(opt) {
			// 恢复上次未提交的批量收货单记录
			if(uni.getStorageSync('orderTempData')){
				console.log('上次未提交的批量收货单记录：',uni.getStorageSync('orderTempData'))
				const obj = uni.getStorageSync('orderTempData');
				if(obj.details.length > 0){
					this.hasRecore = true
				}
				this.common.goodsList = obj.details || []
				// this.$nextTick(()=>{
					if(obj.details.length > 0){
						let arr = []
						obj.details.forEach((item)=>{
							arr.push(item)
						})
						this.defaultChoose = arr
					}
				// })
			}
			
			// this.batchPrint({
			// 	"amount": 2137,
			// 	"order": [{
			// 			"barcode": "",
			// 			"id": 14665,
			// 			"name": "测试",
			// 			"userid": 306,
			// 			"licenseplate": "",
			// 			"usermobile": "13750105624",
			// 			"staffname": "管理员",
			// 			"packname": "凤城·青猿再生资源分拣中心",
			// 			"number": "PO202507190020",
			// 			"icnumber": "0312261632",
			// 			"createddatetime": "2025-07-19 11:26:10",
			// 			"grossweight": 12131,
			// 			"tareweight": 10115,
			// 			"netweight": 2016,
			// 			"weight": 20160,
			// 			"ismodifyprice": false,
			// 			"price": 10,
			// 			"typenames": "金属",
			// 			"productname": "废铁",
			// 			"deductionweight": 0,
			// 			"deductionratio": 0,
			// 			"printed": false,
			// 			"amount": 2016,
			// 			"state": "已收货",
			// 			"paymented": false,
			// 			"paymentusername": "",
			// 			"paymenttime": null,
			// 			"accountname": null,
			// 			"actual": 0,
			// 			"remarks": "",
			// 			"productid": 37,
			// 			"codeindex": 0,
			// 			"one": [],
			// 			"two": [],
			// 			"paypic": [],
			// 			"process": [{
			// 					"createddatetime": "2025-07-19 11:26:10",
			// 					"staffname": "管理员",
			// 					"customname": "测试",
			// 					"remarks": "代客户下单，操作人：管理员",
			// 					"state": "代客户下单"
			// 				},
			// 				{
			// 					"createddatetime": "2025-07-19 11:26:10",
			// 					"staffname": "管理员",
			// 					"customname": "测试",
			// 					"remarks": "代客户下单，操作人：管理员",
			// 					"state": "代客户下单"
			// 				}
			// 			]
			// 		},
			// 		{
			// 			"barcode": "",
			// 			"id": 14666,
			// 			"name": "测试",
			// 			"userid": 306,
			// 			"licenseplate": "",
			// 			"usermobile": "13750105624",
			// 			"staffname": "管理员",
			// 			"packname": "青猿测试站点",
			// 			"number": "PO202507190021",
			// 			"icnumber": "0312261632",
			// 			"createddatetime": "2025-07-19 11:26:11",
			// 			"grossweight": 1000,
			// 			"tareweight": 900,
			// 			"netweight": 100,
			// 			"weight": 100,
			// 			"ismodifyprice": false,
			// 			"price": 1.21,
			// 			"typenames": "金属",
			// 			"productname": "铜",
			// 			"deductionweight": 0,
			// 			"deductionratio": 0,
			// 			"printed": false,
			// 			"amount": 121,
			// 			"state": "已收货",
			// 			"paymented": false,
			// 			"paymentusername": "",
			// 			"paymenttime": null,
			// 			"accountname": null,
			// 			"actual": 0,
			// 			"remarks": "",
			// 			"productid": 1,
			// 			"codeindex": 0,
			// 			"one": [],
			// 			"two": [],
			// 			"paypic": [],
			// 			"process": [{
			// 					"createddatetime": "2025-07-19 11:26:11",
			// 					"staffname": "管理员",
			// 					"customname": "测试",
			// 					"remarks": "代客户下单，操作人：管理员",
			// 					"state": "代客户下单"
			// 				},
			// 				{
			// 					"createddatetime": "2025-07-19 11:26:11",
			// 					"staffname": "管理员",
			// 					"customname": "测试",
			// 					"remarks": "代客户下单，操作人：管理员",
			// 					"state": "代客户下单"
			// 				}
			// 			]
			// 		}
			// 	]
			// })
		},
		onUnload() {
			console.log('页面卸载...')
			this.completeOrder()
		},
		methods: {
			// 关键词搜索
			searchKey(key) {
				this.telSearch.searchList = []
				this.telSearch.isNotReg = false
				// if(key.length > 3){
				this.loading = true
				uni.$u.http.post('Pack/Custom/List', {
					PageIndex: 1,
					PageSize: 10,
					key: key
				}).then((res) => {
					this.telSearch.searchList = res.datas.rows
					// this.telSearch.bindenterprises = res.bindenterprises
					if (this.telSearch.searchList.length == 0) {
						if (uni.$u.test.mobile(key)) {
							this.telSearch.isNotReg = true
						}
						this.tips = '找不到结果'
					}
					this.loading = false
				}).catch(() => {
					this.loading = false
				})
				// }else{
				// 	this.loading = false
				// 	this.tips = '请输入完整电话号码搜索'
				// }
			},
			// 选择搜索结果
			chooseUser(item) {
				console.log('选择搜索结果',item)
				this.userInfo = {
					id: item.id,
					name: item.name,
					mobile: item.mobile
				}
				this.telSearch.show = false
			},
			closeModal(state){
				// this.alertModel.show = false
			},
			confirmModal(){
				// this.alertModel.show = false
			},
			getCode(obj){
				console.log('getCode',obj)
				switch (obj.type){
					case 'IC':
						this.devices.devices.IC.value = obj.code
						break;
					case 'QrCode':
						this.devices.devices.ScanCode.value = obj.code
						break;
					default:
						this.devices.devices.ScanCode.value = obj.code
						break;
				}
				
			},
			// 保存未完成订单的数据
			saveTempData(){
				console.log('保存未完成订单的数据...')
				uni.setStorageSync('orderTempData',{
					userInfo: this.userInfo,
					details: this.common.goodsList
				})
			},
			// 刷卡
			async IC(code) {
				// 当正在进行IC绑定时，仅获取读数
				uni.showLoading({
					title: '加载中,请稍后...'
				})
				// 防抖处理，1000ms内只触发一次
				// uni.$u.throttle(async () => {
					if (this.isSteady == false) {
						this.playAudio('v1')
						uni.showToast({
							title: '请等待磅秤稳定',
							icon: 'none'
						})
						uni.hideLoading()
						return
					}
					uni.$u.http.get('/Iot/IC/GetUser?code=' + code).then(async (res) => {
						// 皮重和毛重不能为0
						try {
							console.log('GetUserRes', res)
							let datas = res.datas
							
							if(datas.usertype == "打包站"){
								throw Error('admin')
							}
							if(datas.usestate == "已冻结"){
								throw Error('usestate')
							}
							if (datas.id) {
								// this.submitOrder({
								// 	type: 2,
								// 	icCode: datas.iccode,
								// 	userid: datas.id,
								// 	mobile: datas.mobile,
								// 	name: datas.name,
								// 	weight: this.weight
								// })
								
								this.userInfo = {
									id: datas.id,
									code: code,
									name: datas.name,
								}
								uni.showToast({
									title: '刷卡成功'
								})
							}else{
								throw Error()
							}
						} catch (e) {
							console.log('err',e)
							let param = {
								iconName: 'close-circle-fill',
								iconColor: '#f56c6c'
							}
							if(e == 'Error: admin'){
								param.title = '请勿使用登录IC卡录入'
							}else if(e == 'Error: usestate'){
								param.title = '该用户已经停用'
							} else{
								param.title = '不可使用未录入的IC卡'
							}
							this.$refs.alert.open(param)
						}
					}).catch((err) => {
						console.log('IC卡读取失败', err)
						this.$refs.alert.open({
							title: '读卡失败',
							content: err?.errMsg,
							iconName: 'close-circle-fill',
							iconColor: '#f56c6c'
						})
					}).finally(()=>{
						uni.hideLoading()
					})
				// },1000)
			},
			//扫码
			async scan(code) {
				// 防抖处理，1000ms内只触发一次
				uni.$u.throttle(async () => {
					if (this.isSteady == false) {
						this.playAudio('v1')
						uni.showToast({
							title: '请等待磅秤稳定',
							icon: 'none'
						})
						return
					}
					this.startIC = false;
					console.log('scanCode:',code)
					uni.$u.http.get('/Pack/QrCode/GetInfo?code=' + code).then(async (res) => {
						console.log('GetQRCodeInfo',res)
						
						let datas = res.datas
						if(datas.type == 1){ //客户二维码
							this.userInfo = {
								id: datas.data.userid,
								code: code,
								name: datas.data.name,
							}
							uni.showToast({
								title: '刷码成功'
							})
						}else if(datas.type == 3){ //订单条形码,查看详情
							uni.$u.http.post('/Pack/Order/Details',{
								orderId: datas.data.id
							}).then((res)=>{
								console.log('获取订单详情',res)
								
								let datas = res.datas
								if(datas.state == '已确定' || datas.state == '已收货'){
									this.print(datas)
								}
							})
						}else{
							this.$refs.alert.open({
								title: '出错了',
								content: '请用客户二维码扫码建单',
								iconName: 'close-circle-fill',
								iconColor: '#f56c6c'
							})
						}
					}).catch((err)=>{
						console.log('catch',err)
						this.$refs.alert.open({
							title: '扫码读取失败',
							content: err?.errMsg,
							iconName: 'close-circle-fill',
							iconColor: '#f56c6c'
						})
					})
				}, 1000)
			},
			// 打印小票
			print(data){
				this.printForm = data
				this.loading = true
				this.loadingText = "打印中,请稍后...",
				uni.$u.http.get('/Pack/Order/PrintOrder?orderId='+this.printForm.id).then((res)=>{
					if(this.devices.setting.Print.open == false){
						// this.$refs.alert.open({
						// 	title: '订单完成',
						// 	content: '如需打印请设置开启打印',
						// 	iconName: 'checkmark-circle-fill',
						// 	iconColor: '#5ac725',
						// 	index: 1,
						// 	showCancel: false
						// })
						
					}else{
						this.printAction(this.devices.setting.Print.printNumber)
						// setTimeout(()=>{
						// 	this.back()
						// },1000)
					}
				}).catch((err)=>{
					console.log('打印失败了',err)
					uni.showToast({
						title: '打印失败',
						icon: 'none'
					})
					// this.$refs.alert.open({
					// 	title: '打印失败',
					// 	content: err.msg,
					// 	iconName: 'close-circle-fill',
					// 	iconColor: '#f56c6c',
					// 	index: 1,
					// 	showCancel: false
					// })
					this.loading = false
				}).finally(()=>{
					this.loading = false
				})
			},
			// 执行打印,i为打印次数
			printAction(i = 1){
				console.log('打印小票...')
				let contentDataArr = [
					{
						"method": "SetClean"
					},
					{
						"method": "SetSizetext",
						"param": [1,1]
					},
					{
						method: "PrintString",
						param: ["第"+i+"联", 0]
					},
					{
						"method": "PrintChargeRow",	
					},
					{
						method: "PrintString",
						param: [this.printForm.packname, 0]
					},
					{
						"method": "PrintChargeRow",	
					},
					{
						method: "PrintString",
						param: ["客户："+this.printForm.name, 0]
					},
					{
						"method": "PrintChargeRow",	
					},
					{
						method: "PrintString",
						param: ["编号："+this.printForm.number, 0]
					},
					{
						"method": "PrintChargeRow",	
					},
					// {
					// 	method: "PrintString",
					// 	param: ["店员:"+this.common.userdetail.username, 0]
					// },
					// {
					// 	"method": "PrintChargeRow",	
					// },
					{
						method: "PrintString",
						param: ["进厂日期:"+uni.$u.timeFormat(this.printForm.createddatetime, 'yyyy-mm-dd'), 0]
					},
					{
						"method": "PrintChargeRow",	
					},
					{
						method: "PrintString",
						param: ["进厂时间:"+uni.$u.timeFormat(this.printForm.createddatetime, 'hh:MM:ss'), 0]
					},
					{
						"method": "PrintChargeRow",	
					},
					{
						method: "PrintString",
						param: ["出厂时间:"+uni.$u.timeFormat(new Date().getTime(), 'hh:MM:ss'), 0]
					},
					{
						"method": "PrintChargeRow",	
					},
					{
						method: "PrintString",
						param: ["回收品类:"+this.printForm.typenames+'-'+this.printForm.productname, 0]
					},
					{
						"method": "PrintChargeRow",	
					},
					{
						method: "PrintString",
						param: ["毛重(KG):"+this.printForm.grossweight, 0]
					},
					{
						"method": "PrintChargeRow",	
					},
					{
						method: "PrintString",
						param: ["皮重(KG):"+this.printForm.tareweight, 0]
					},
					{
						"method": "PrintChargeRow",	
					},
					{
						method: "PrintString",
						param: ["净重(KG):"+this.printForm.netweight, 0]
					},
					{
						"method": "PrintChargeRow",	
					},
					{
						method: "PrintString",
						param: ["扣重(KG):"+this.printForm.deductionweight, 0]
					},
					{
						"method": "PrintChargeRow",	
					},
					// {
					// 	method: "PrintString",
					// 	param: ["扣点:"+this.printForm.deductionratio+"%", 0]
					// },
					// {
					// 	"method": "PrintChargeRow",	
					// },
					{
						method: "PrintString",
						param: ["实重(KG):"+this.printForm.weight, 0]
					},
					{
						"method": "PrintChargeRow",	
					},
					{
						method: "PrintString",
						param: ["单价(元/KG):"+this.printForm.price, 0]
					},
					{
						"method": "PrintChargeRow",	
					},
					{
						method: "PrintString",
						param: ["金额(元):"+this.printForm.amount, 0]
					},
					{
						"method": "PrintChargeRow",	
					},
					{
						method: "SetReadZKmode", //设置汉字模式
						param: [1]
					},
					{
						method: "PrintFeedline",
						param: [2]
					},
					{
					    "method": "SetLeftmargin",
					    "param": [
					        120
					    ]
					},
					{
						method: "PrintBase64Pic",
						param: [
							this.printForm.barcode
						]
					},
					{
						"method": "PrintFeedline",
						"param": [6]
					},
					{
						"method": "PrintCutpaper",
						"param": [0]
					}
				]
				
				this.devices.Print(contentDataArr).then((res)=>{
					var num = i - 1
					// 当i > 1为false时，已打印了i次
					if(i > 1){
						this.printAction(num)
					}else{
						this.loading = false
						this.loadingText = "已完成打印,等待上传截图凭证...",
						this.sendMsg('reloadOrder','已完成打印')
					}
				}).catch((err)=>{
					// this.$refs.alert.open({
					// 	title: '打印失败',
					// 	content: '请检查打印机是否正常工作',
					// 	iconName: 'close-circle-fill',
					// 	iconColor: '#f56c6c',
					// 	index: 1
					// })
					uni.showToast({
						title: '打印失败',
						icon: 'none'
					})
					this.loading = false
				})
			},
			// 选择回收品回调
			confirmChoose(chooseType) {
				this.common.goodsList = chooseType
				// 选择品类后直接打开称重页面
				if(this.goodsList.length > 0){
					let index = this.goodsList.indexOf(this.goodsList[this.goodsList.length - 1])
					this.$refs.goodsTableList.getWeigh(index)
				}
			},
			// 获取总价
			getTotal(data) {
				this.total = 0
				data.forEach((item) => {
					if (item.weight) {
						this.total += Number(item.price) * Number(item.weight)
					}
				})
				this.total = tool.formatMoney(this.total)
			},
			// 获取图片
			getPic(obj) {
				console.log('上传的图片数组', obj)
				let hasPic = this.tempPic.find((cell)=>cell.id == obj.id)
				if(hasPic){
					hasPic.pic = obj.pic
				}else{
					this.tempPic.push(obj)
				}
			},
			// 查看图片
			seePhoto(index) {
				this.pic = []
				let urls = []
				this.tempPic.forEach((item) => {
					if(this.goodsList.filter((cell)=>cell.id == item.id).length > 0){
						this.pic.push(item.pic)
						urls.push(config.fileURL + item.pic)
					}
				})
				uni.previewImage({
					current: index,
					urls: urls
				});
			},
			// 赋值图片路径
			imgURL(img) {
				// console.log('赋值图片路径',config.fileURL + img)
				return config.fileURL + img
			},
			// 弹出确认弹窗
			confirmOrderShow() {
				console.log('弹出确认弹窗')
				let check = true

				// 检查回收物清单的重量是否填写
				try {
					this.goodsList.forEach(item => {
						if (item.isweighing) {
							if (item.weight == null || item.weight == 0) {
								uni.showToast({
									title: '请填写' + item.name + '的重量',
									icon: 'none'
								})
								throw Error()
							}
						} else {
							if (item.weight == null || item.weight == 0) {
								uni.showToast({
									title: '请填写' + item.name + '的数量',
									icon: 'none'
								})
								throw Error()
							}
						}

					})
				} catch (error) {
					check = false;
				}

				if (!check) {
					return
				}
				this.pic = []
				this.tempPic.forEach((item) => {
					if(this.goodsList.filter((cell)=>cell.id == item.id).length > 0){
						this.pic.push(item.pic)
					}
				})
				this.confirmOrder = true
			},
			// 发起提交
			startConfimCreate() {
				console.log('发起提交')
				this.confirmCreate()
			},
			// 确认提交
			confirmCreate() {
				uni.showLoading({
					title: '提交中，请稍后...',
					mask: true
				})
				if(this.userInfo.id == 0){
					uni.showToast({
						title: '请刷卡或扫客户二维码',
						icon: 'none'
					})
					return
				}

				let params = {
					userId: this.userInfo.id,  //旧版本参数，后续删除
					customId: this.userInfo.id,
					details: []
				}
				if(this.goodsList.length > 0){
					this.goodsList.forEach((item)=>{
						params.details.push({
							...item,
							"productId": item.id,
							"grossWeight": item.weight,
							"price": item.price,
							"tareWeight": item.tareWeight,
							"deductionWeight": 0,
							"deductionRatio": 0
						})
					})
				}
				console.log('确认提交时的参数',params)
				this.orderForm = params
				uni.$u.http.post('/Pack/Order/Recovery', this.orderForm).then((res) => {
					console.log('提交成功',res)
					
					uni.showToast({
						title: '提交成功'
					})
					this.completeOrder(true)
					this.confirmOrder = false
					
					// 打印批量收货单
					this.batchPrint(res.datas,this.devices.setting.Print.printNumber)
					
					uni.hideLoading()
				}).catch((err) => {
					uni.hideLoading()
				})
			},
			// 打印批量收货单
			batchPrint(data,i=1){
				console.log('打印批量收货单',data)
				const printData = data
				
				let order = data.order //收货单列表
				let packname = order[0].packname //打包站名称
				let name = order[0].name //客户名称
				let staffname = order[0].staffname //当前登录店员
				let totalAmount = data.amount //合计金额
				let icnumber = order[0].icnumber //批量收货单编号
				let createddatetime = order[0].createddatetime //收货时间
				
				let priceData = [
					{
						method: "SetClean"//清理缓存，清除之前设置的参数
					},
					{
						method: "SetLeftmargin",
						param: [20]
					},
					{
						method: "SetReadZKmode", //设置汉字模式
						param: [0]
					},
					// {
					// 	method: "SetSizetext" ,
					// 	param: [1,1]
					// },
					
					{
						method: "SetSizechinese" ,
						param: [1,1,0,1]
					},
					{
						method: "SetAlignment",
						param: [1]
					},
					{
						method: "SetBold" ,
						param: [1]
					},
					{
						method: "PrintString",
						param: [packname, 0]
					},
					{
						method: "SetBold" ,
						param: [0]
					},
					{
						method: "PrintChargeRow",	
					},
					// {
					// 	method: "SetSizetext" ,
					// 	param: [0,0]
					// },
					{
						method: "SetAlignment",
						param: [0]
					},
					{
						method: "PrintFeedline",
						param: [1]
					},
					{
						method: "PrintString",
						param: ["客户名称："+name, 0]
					},
					{
						method: "PrintChargeRow",	
					},
					// {
					// 	method: "PrintString",
					// 	param: ["卡号："+icnumber, 0]
					// },
					// {
					// 	method: "PrintChargeRow",	
					// },
					{
						method: "PrintString",
						param: ["打印时间："+createddatetime, 0]
					},
					{
						method: "PrintChargeRow",
					},
					{
						method: "SetAlignment",
						param: [1]
					},
					// {
					// 	method: "SetSizechar" ,
					// 	param: [0,0,0,0]
					// },
					{
						method: "PrintString",
						param: ["--------------------------------------------", 0]
					},
					// {
					// 	method: "SetSizechar" ,
					// 	param: [1,1,0,1]
					// },
					{
						method: "PrintChargeRow",	
					},
					{
						method: "SetAlignment",
						param: [0]
					},
					// {
					// 	method: "SetHTseat", //设置水平制表位置
					// 	param: [
					// 		[15, 29, 40], 3
					// 	]
					// },
					// {
					// 	method: "PrintString",
					// 	param: ["回收品类", 1]
					// },
					// {
					// 	method: "PrintNextHT" //执行到下一个水平制表位置
					// },
					// {
					// 	method: "PrintString",
					// 	param: ["单价", 1]
					// },
					// {
					// 	method: "PrintNextHT" //执行到下一个水平制表位置
					// },
					// {
					// 	method: "PrintString",
					// 	param: ["数量", 1]
					// },
					// {
					// 	method: "PrintNextHT" //执行到下一个水平制表位置
					// },
					// {
					// 	method: "PrintString",
					// 	param: ["金额", 0]
					// },
					// {
					// 	method: "SetLinespace", 
					// 	param: [30]
					// },
				]
				order.forEach((item)=>{
					priceData.push(
						// {
						// 	method: "SetSizechinese" ,
						// 	param: [0,0,0,0]
						// },
						{
							method: "PrintString",
							param: ['收货编号：'+item.number, 0]
						},
						{
							method: "PrintChargeRow",	
						},
						{
							method: "PrintString",
							param: ['可回收物：'+item.typenames+'-'+item.productname, 0]
						},
						{
							method: "PrintChargeRow",	
						},
						// {
						// 	method: "SetSizechinese" ,
						// 	param: [0,0,0,1]
						// },
						{
							method: "SetAlignment",
							param: [0]
						},
						{
							method: "PrintString",
							param: ['单价：'+item.price.toFixed(2)+'            '+'重量：'+item.weight.toFixed(2), 0]
						},
						{
							method: "PrintChargeRow",	
						},
						{
							method: "SetAlignment",
							param: [0]
						},
						// {
						// 	method: "SetSizechar" ,
						// 	param: [1,1,0,1]
						// },
						{
							method: "PrintString",
							param: ['金额：'+item.amount.toFixed(2), 0]
						},
						{
							method: "PrintChargeRow",	
						},
						// {
						// 	method: "SetSizechar" ,
						// 	param: [0,0,0,0]
						// },
						{
							method: "PrintString",
							param: ["--------------------------------------------", 0]
						},
						// {
						// 	method: "SetSizechar" ,
						// 	param: [1,1,0,1]
						// },
					)
				})
				
				priceData.push({
					method: "SetLinespace", 
					param: [30]
				},{
					method: "PrintChargeRow",	
				},{
					method: "SetAlignment",
					param: [0]
				},
				// {
				// 	method: "PrintString",
				// 	param: ["卖货客户："+name, 0]
				// },
				// {
				// 	method: "PrintChargeRow",	
				// },
				{
					method: "SetSizechar" ,
					param: [1,1,0,1]
				},
				{
					method: "PrintString",
					param: ["合计金额："+totalAmount+"元", 0]
				},
				{
					method: "PrintChargeRow",
				},
				// ,{
				// 	method: "SetAlignment",
				// 	param: [1]
				// },
				// {
				// 	method: "PrintString",
				// 	param: ["--------------------------------------------", 0]
				// },{
				// 	method: "PrintChargeRow",	
				// },{
				// 	method: "SetAlignment",
				// 	param: [0]
				// },{
				// 	method: "PrintString",
				// 	param: ["欢迎再次光临--服务电话：400-800-3039", 0]
				// },
				{
					method: "PrintFeedline",
					param: [6]
				},{
					method: "PrintCutpaper", //打印切纸
					param: [0]
				})
				
				console.log('批量打印命令',priceData)
				this.devices.Print(priceData).then((res)=>{
					var num = i - 1
					// 当i > 1为false时，已打印了i次
					if(i > 1){
						this.batchPrint(printData,num)
					}else{
						this.loading = false
						// this.loadingText = "已完成打印,等待上传截图凭证...",
						// this.sendMsg('reloadOrder','已完成打印')
					}
				}).catch((err)=>{
					uni.showToast({
						title: '打印失败',
						icon: 'none'
					})
					// this.$refs.alert.open({
					// 	title: '打印失败',
					// 	content: '请检查打印机是否正常工作',
					// 	iconName: 'close-circle-fill',
					// 	iconColor: '#f56c6c',
					// 	index: 1
					// })
					this.loading = false
				})
			},
			// 取消提交
			cancelOrder() {
				uni.showModal({
					content: '确定要清空录入信息吗？',
					success: (res) => {
						if (res.confirm) {
							this.completeOrder(true)
						} else if (res.cancel) {

						}
					}
				})
			},
			// 完成订单后
			completeOrder(clean = false){
				this.common.goodsList = []
				this.common.info = {}
				this.pic = []
				this.userInfo = {
					id: 0,
					code: '',
					details:{}
				}
				if(clean == true){
					uni.removeStorageSync('orderTempData')
					this.hasRecore = false
				}
			}
		}
	}
</script>

<style lang="scss" scoped>
	// 环形称重计
	.circle-progress-box{
		position: relative;
		padding-top: 60rpx;
		height: 220rpx;
		overflow: hidden;
		
		/* 下面的度数根据实际进度调整，例如25%代表进度为一半 */
		--progress: 20%;
		--border-shadow: 0px 2px 15px 6px rgba(112,112,112,0.1);
		.circle-bg{
			position: absolute;
			width: 500rpx;
			height: 500rpx;
			border-radius: 50%;
			background: #f3f4f5;
			top: 40rpx;
			left: 50%;
			margin-left: -250rpx;
		}
		
		.circle-progress {
			position: relative;
			width: 440rpx;
			height: 440rpx;
			border-radius: 50%;
			background-color: #eee;
			overflow: hidden;
			transform: rotate(-90deg);
			margin: 0 auto;
			&:before{
				content: '';
				width: 80%;
				height: 80%;
				position: absolute;
				z-index: 2;
				top: 10%; 
				left: 10%;
				background-color: #fff;
				border-radius: 50%;
			}
			// &:after{
			// 	content: '';
			// 	width: 50%;
			// 	height: 100%;
			// 	background-color: #fff;
			// 	position: absolute;
			// 	top: 0;
			// 	left: 0;
			// }
		}
		
		.progress-bar {
			position: absolute;
			top: 0; 
			left: 0;
			width: 100%;
			height: 100%;
			transition: all 0.5s;
			border-radius: 50%;
			background-image: conic-gradient(
				#fd7e14 0% var(--progress), /* 进度颜色 */
				#2ab6b3 var(--progress) 100%    /* 未完成部分颜色 */
			);
		}
		
		.weight{
			position: absolute;
			left: 50%;
			bottom: -80rpx;
			color: #000;
			background-color: #fff;
			width: 200rpx;
			height: 200rpx;
			margin-left: -100rpx;
			box-shadow: var(--border-shadow);
			border-radius: 50%;
			display: flex;
			justify-content: center;
			align-items: center;
			line-height: 1em;
			z-index: 2;
			flex-direction: column;
			.num{
				font-weight: bold;
				font-size: 50rpx;
				&.yes{
					// color: $uni-type-success;
				}
				&.no{
					color: $uni-color-error;
				}
			}
			.unit{
				font-size: 20rpx;
			}
		}
	
		.pointer{
			background-color: #fff;
			box-shadow: var(--border-shadow);
			position: absolute;
			bottom: 0;
			right: 50%;
			width: 200rpx;
			height: 10rpx;
			transform-origin: right;
			transform: rotate(0deg);
			z-index: 1;
			border-radius: 10rpx;
		}
	}
	
	.u-font-xl {
		font-size: 24rpx;
		font-weight: bold;
	}

	.u-font-sm {
		font-size: 16rpx;
	}

	.page {
		display: flex;
		flex-direction: column;
	}

	.link {
		color: $uni-color-blue;
		text-decoration: underline;

		&:active {
			opacity: 0.8;
		}
	}

	// 头部样式
	.header {
		background: #10beca;
		display: flex;
		flex-direction: row;
		padding: 0 10rpx;
		
		&_logo {
			height: 30px;
			width: 70px;
			border-radius: 50%;
			margin-right: 15rpx;
		}

		&_time {
			color: #ffffff
		}
		
		.con{
			display: flex;
			height: 100rpx;
			justify-content: center;
			align-items: center;
			width: 100%;
		}
	}

	// 主体样式
	.main {
		display: flex;
		flex: 1;

		&_left {
			width: 230rpx;
			display: flex;
			flex-direction: column;
			// border-right: 1px solid $uni-light-color;
			// flex: 1;

			&_head {
				display: flex;
				flex-direction: row;
				padding: 20rpx;
				line-height: 1.4em;
				height: 80rpx;
				box-sizing: border-box;
				background-color: #fff;
			}

			&_content {
				display: flex;
				flex-direction: row;
				flex: 1;
			}
		}

		&_right {
			flex: 1;
			background-color: #fff;

			&_weight {
				border-bottom: 10rpx solid #f4f4f5;

				&_header {
					padding: 24rpx;
					line-height: 1em;

					// height: 80rpx;
					box-sizing: border-box;

					&_font {
						font-size: 28rpx;
						font-weight: bold;
					}
				}

				&_number {
					display: flex;
					align-items: baseline;
					justify-content: center;
					padding: 30rpx 0;

					.num {
						font-size: 100rpx;
						&.yes{
							// color: $uni-type-success;
						}
						&.no{
							color: $uni-color-error;
						}
					}

					.unit {
						font-size: 24rpx;
					}
				}
			}

			&_userInfo {
				&_header {
					padding: 24rpx;
					line-height: 1em;

					// height: 80rpx;
					box-sizing: border-box;

					&_font {
						font-size: 28rpx;
						font-weight: bold;
					}
				}

				.user-msg {
					padding: 20rpx;
					align-items: center;
				}
			}
		}
	}

	.bottom-box {
		.fixed-container {
			position: fixed;
			bottom: 0;
			background-color: #fff;
			padding-top: 0;
			width: calc(100% - 220rpx);
			height: 100rpx;
			z-index: 99;
			box-shadow: 0 0 16rpx #e7e7e7;
		}

		.fixed-placeholder {
			height: 100rpx;
			width: calc(100% - 220rpx);
			// margin-top: 30rpx;
		}

		.total {
			display: flex;
			border: 1px solid $uni-color-main;
			line-height: 60rpx;
			padding-left: 30rpx;
			padding-right: 0;
			margin: 15rpx;
			border-radius: 48rpx;

			.total-price {
				flex: 1;
				color: $uni-color-orange;
				font-weight: bold;

				.unit {
					font-size: 20rpx;
				}

				.num {
					font-size: 34rpx;
				}
			}

			.btn {
				background-color: $uni-color-main;
				color: #fff;
				border-radius: 48rpx;
				padding: 0 40rpx;
				border-top-left-radius: 0;
				border-bottom-left-radius: 0;
				font-size: 20rpx;
				height: 66rpx;
				line-height: 66rpx;
			}
		}

		.btn-group {
			padding-left: 15rpx;
			padding-right: 15rpx;
			padding-bottom: 15rpx;
		}
	}

	.circle {
		width: 40rpx;
		height: 40rpx;
		border: 1px solid #666;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;

		&.on {
			border-color: $uni-color-blue;
			background-color: $uni-color-blue;
		}
	}

	// 确认订单
	.confirm-order {
		max-height: 90vh;
		text-align: center;

		.price {
			font-weight: bold;
		}

		.bold {
			font-weight: bold;
		}

		.goods-name {
			font-weight: bold;
		}

		.goods-price {
			color: $uni-color-orange;
			font-size: 32rpx;
			font-weight: bold;
		}


		.price-tag {
			display: flex;
			justify-content: flex-end;

			.item {
				display: block;
				padding: 0 10rpx;
				height: 34rpx;
				line-height: 34rpx;
				color: #ffffff;
				font-size: 20rpx;
				border-radius: 6rpx;
				text-align: center;
				margin-left: 30rpx;
				background-color: #3191fd;
			}
		}

		.settlement-List {
			.item {
				margin-left: 20rpx;
				margin-right: 20rpx;
				padding-top: 20rpx;
				padding-bottom: 20rpx;
				border-bottom: 1px solid #f4f4f5;
			}
		}
	}

	// 提交订单栏
	.navigation-sticky-box {
		position: sticky;
		z-index: 99;
		bottom: 0;
		background: #fff;
		padding-bottom: 20rpx;

		.navigation {
			display: flex;
			width: 700rpx;
			// background-color: #ffffff;
			padding: 20rpx 0 30rpx;
			margin: 10rpx auto;

			.left {
				display: flex;
				align-items: center;
				font-size: 30rpx;
				flex: 1;
				background-color: #fff;
				border-top-left-radius: 50rpx;
				border-bottom-left-radius: 50rpx;
				box-shadow: $uni-color-border-shadow;

				.item {
					margin: 0 30rpx;
					display: flex;

					.icon {
						position: relative;
					}

					&.car {
						text-align: center;
						position: relative;

						.car-num {
							position: absolute;
							top: -10rpx;
							right: -10rpx;
						}
					}
				}
			}

			.right {
				display: flex;
				font-size: 28rpx;
				align-items: center;

				.btn {
					line-height: 100rpx;
					padding: 0 30rpx;
					border-radius: 50rpx;
					color: #ffffff;
					border-top-left-radius: 0;
					border-bottom-left-radius: 0;
					width: 240rpx;
					text-align: center;
				}

				.cart {
					background-color: #ed3f14;
					margin-right: 30rpx;
				}

				.buy {
					background-color: #ff7900;
				}
			}
		}
	}

	// 分割
	.divider {
		height: 1px;
		border: 1px dotted #f4f4f5;
		position: relative;

		&:after {
			content: '';
			width: 20rpx;
			height: 20rpx;
			background: #f4f4f5;
			position: absolute;
			left: -12rpx;
			top: -12rpx;
			border-radius: 50%;
		}

		&:before {
			content: '';
			width: 20rpx;
			height: 20rpx;
			background: #f4f4f5;
			position: absolute;
			right: -12rpx;
			top: -12rpx;
			border-radius: 50%;
		}
	}
	.search-list{
		height: 80vh;
	}
</style>